<template>
  <div class="device-monitor-container">
    <el-card shadow="never" class="monitor-overview-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-statistic title="设备总数" :value="overviewData.totalDevices" />
        </el-col>
        <el-col :span="6">
          <el-statistic title="正常运行" :value="overviewData.normalDevices" />
        </el-col>
        <el-col :span="6">
          <el-statistic title="异常设备" :value="overviewData.abnormalDevices" />
        </el-col>
        <el-col :span="6">
          <el-statistic title="停机维护" :value="overviewData.maintenanceDevices" />
        </el-col>
      </el-row>
    </el-card>

    <el-card shadow="never" class="chart-card">
      <template #header>
        <div class="card-header">
          <span>设备运行状态分布</span>
        </div>
      </template>
      <div ref="deviceStatusChart" style="width: 100%; height: 300px;"></div>
    </el-card>

    <el-card shadow="never" class="status-list-card">
      <template #header>
        <div class="card-header">
          <span>当前异常设备列表</span>
          <el-button type="primary" link @click="goToFaultProcess">查看更多故障</el-button>
        </div>
      </template>
      <!-- 使用 store 的 loading 状态 -->
      <el-table :data="abnormalDevicesList" v-loading="deviceStore.loading" stripe :show-header="true" empty-text="当前无异常设备">
        <el-table-column prop="eqname" label="设备名称" min-width="150" show-overflow-tooltip />
        <el-table-column prop="eqmodel" label="型号" width="120" />
        <el-table-column prop="eqtype" label="设备类型" width="120" />
        <el-table-column prop="eqstatus" label="状态" width="100">
          <template #default="{ row }">
            <!-- 使用 store 的 `getStatusTagType` 和 `getDeviceStatusLabel` -->
            <el-tag :type="deviceStore.getStatusTagType(row.eqstatus)">{{ deviceStore.getDeviceStatusLabel(row.eqstatus) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="eqtime" label="购买日期" width="160">
            <template #default="{ row }">
                <!-- 保持日期格式化一致 -->
                {{ row.eqtime ? row.eqtime.split('T')[0] : 'N/A' }}
            </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleViewDetail(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-footer" v-if="abnormalPagination.total > abnormalPagination.pageSize">
        <el-pagination
          v-model:current-page="abnormalPagination.pageNo"
          v-model:page-size="abnormalPagination.pageSize"
          :small="true"
          :disabled="deviceStore.loading"
          :background="false"
          layout="prev, pager, next"
          :total="abnormalPagination.total"
          @current-change="fetchAbnormalDevices"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import * as echarts from 'echarts';
import { useRouter } from 'vue-router';
// 导入 Pinia store
import { useDeviceStore } from '@/stores/modules/device';
// storeToRefs 如果只访问 state 的响应式属性时才需要，这里直接通过 deviceStore 访问 action 和 helper
// import { storeToRefs } from 'pinia'; 

const router = useRouter();
// 获取 store 实例
const deviceStore = useDeviceStore();

// 可以选择性地将 store 中的 loading 状态解构出来，或者直接使用 deviceStore.loading
// const { loading } = storeToRefs(deviceStore); 

// --- 概览数据 ---
const overviewData = reactive({
  totalDevices: 0,
  normalDevices: 0,
  abnormalDevices: 0,
  maintenanceDevices: 0,
});

// --- ECharts 图表 ---
const deviceStatusChart = ref(null);
let myChart = null;

const initChart = () => {
  if (deviceStatusChart.value) {
    if (myChart) {
      myChart.dispose();
    }
    myChart = echarts.init(deviceStatusChart.value);
    myChart.setOption({
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        // 从 store 的 DeviceStatusMap 中获取图例名称
        data: Object.values(deviceStore.DeviceStatusMap).map(item => item.label), 
      },
      series: [
        {
          name: '设备状态',
          type: 'pie',
          radius: ['50%', '70%'],
          avoidLabelOverlap: false,
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '30',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: [],
          // 颜色顺序与 DeviceStatusMap 的 0, 1, 2 状态对应
          color: ['#67C23A', '#F56C6C', '#E6A23C'] // 正常运行 (0), 异常 (1), 停机维护 (2)
        }
      ]
    });
    window.addEventListener('resize', resizeChart);
  }
};

const resizeChart = () => {
  myChart?.resize();
};

onBeforeUnmount(() => {
  if (myChart) {
    myChart.dispose();
    window.removeEventListener('resize', resizeChart);
  }
});

// 使用从 store 获取的数据更新图表和概览数据
const updateChartData = (data) => {
  const statusCounts = data.reduce((acc, device) => {
    // device.eqstatus 是数字 (0, 1, 2)。使用 getDeviceStatusLabel 转换为对应的字符串标签。
    const statusLabel = deviceStore.getDeviceStatusLabel(device.eqstatus);
    acc[statusLabel] = (acc[statusLabel] || 0) + 1;
    return acc;
  }, {});

  const chartData = [
    { value: statusCounts[deviceStore.getDeviceStatusLabel(0)] || 0, name: deviceStore.getDeviceStatusLabel(0) }, // 正常运行 (0)
    { value: statusCounts[deviceStore.getDeviceStatusLabel(1)] || 0, name: deviceStore.getDeviceStatusLabel(1) }, // 异常 (1)
    { value: statusCounts[deviceStore.getDeviceStatusLabel(2)] || 0, name: deviceStore.getDeviceStatusLabel(2) }, // 停机维护 (2)
  ];

  myChart?.setOption({
    series: [{ data: chartData }]
  });

  overviewData.totalDevices = data.length;
  overviewData.normalDevices = statusCounts[deviceStore.getDeviceStatusLabel(0)] || 0;
  overviewData.abnormalDevices = statusCounts[deviceStore.getDeviceStatusLabel(1)] || 0;
  overviewData.maintenanceDevices = statusCounts[deviceStore.getDeviceStatusLabel(2)] || 0;
};

// --- 异常设备列表 ---
const abnormalDevicesList = ref([]);
// loading 状态直接使用 deviceStore.loading
const abnormalPagination = reactive({
  pageNo: 1, // 与 store 的 searchForm.pageNo 保持一致
  pageSize: 5,
  total: 0,
});

// 获取所有设备数据用于统计图
const fetchAllDevicesForChart = async () => {
    try {
        // 调用 store 的 fetchDeviceList，并获取返回的 records
        // 由于图表需要所有设备数据，这里将 pageSize 设置为足够大的值
        const allDevicesRecords = await deviceStore.fetchDeviceList({
            pageNo: 1,
            pageSize: 9999, // 确保获取所有数据
            eqname: null, eqtype: null, eqstatus: null, eqmodel: null, eqmanufacture: null, 
            sortBy: 'eqid', isAsc: true,
        });
        updateChartData(allDevicesRecords);
    } catch (error) {
        // store 内部已处理 ElMessage 提示，这里可以打印到控制台
        console.error('获取所有设备数据用于统计图失败:', error);
       // ElMessage.error('获取所有设备数据用于统计图失败'); // 可选：如果 store 没有处理这一层错误通知
    }
};

// 获取异常设备列表
const fetchAbnormalDevices = async (currentPage) => {
    try {
        if (currentPage) abnormalPagination.pageNo = currentPage;
        const params = {
            eqstatus: 1, // 关键：使用数字ID 1 代表“异常”
            pageNo: abnormalPagination.pageNo,
            pageSize: abnormalPagination.pageSize,
            eqname: null, eqtype: null, eqmodel: null, eqmanufacture: null, sortBy: 'eqid', isAsc: true,
        };
        // 调用 store 的 fetchDeviceList，并获取返回的 records 作为当前列表数据
        const abnormalRecords = await deviceStore.fetchDeviceList(params);
        abnormalDevicesList.value = abnormalRecords;
        abnormalPagination.total = deviceStore.total; // total 可以在 store 中获取
    } catch (error) {
        console.error('获取异常设备列表失败:', error);
        // ElMessage.error('获取异常设备列表失败'); // 可选
    }
};

onMounted(() => {
  initChart();
  fetchAllDevicesForChart(); // 先获取所有设备用于图表概览
  fetchAbnormalDevices();    // 再获取异常设备列表
});

// 移除本地的 getStatusTagType，直接使用 deviceStore.getStatusTagType
// const getStatusTagType = (status) => { /* ... 移除 ... */ };

const handleViewDetail = async (row) => {
  try {
    // 调用 store 的 fetchDeviceDetail 接口获取详细数据
    const detail = await deviceStore.fetchDeviceDetail(row.eqid); 
    
    ElMessageBox.alert(`
        <style>
          .device-detail-content { font-size: 14px; line-height: 1.8; }
          .device-detail-content p { margin-bottom: 8px; }
          .device-detail-content strong { display: inline-block; width: 100px; text-align: right; margin-right: 15px; color: #606266; }
        </style>
        <div class="device-detail-content">
          <p><strong>设备ID:</strong> ${detail.eqid || 'N/A'}</p>
          <p><strong>设备名称:</strong> ${detail.eqname || 'N/A'}</p>
          <p><strong>设备类型:</strong> ${detail.eqtype || 'N/A'}</p>
          <p><strong>设备描述:</strong> ${detail.eqdiscribe || '无'}</p>
          <p><strong>设备状态:</strong> <span style="font-weight: bold; color: ${deviceStore.getStatusTagType(detail.eqstatus) === 'success' ? '#67C23A' : deviceStore.getStatusTagType(detail.eqstatus) === 'danger' ? '#F56C6C' : '#E6A23C'}">${deviceStore.getDeviceStatusLabel(detail.eqstatus) || 'N/A'}</span></p>
          <p><strong>设备数量:</strong> ${detail.eqcount !== null && detail.eqcount !== undefined ? detail.eqcount : 'N/A'}</p>
          <p><strong>设备价格:</strong> ${detail.eqprice !== null && detail.eqprice !== undefined ? detail.eqprice + ' 元' : 'N/A'}</p>
          <p><strong>设备电压:</strong> ${detail.eqv !== null && detail.eqv !== undefined ? detail.eqv + ' V' : 'N/A'}</p>
          <p><strong>设备电流:</strong> ${detail.eqa !== null && detail.eqa !== undefined ? detail.eqa + ' A' : 'N/A'}</p>
          <p><strong>设备功率:</strong> ${detail.eqw !== null && detail.eqw !== undefined ? detail.eqw + ' W' : 'N/A'}</p>
          <p><strong>设备型号:</strong> ${detail.eqmodel !== null && detail.eqmodel !== undefined ? detail.eqmodel : 'N/A'}</p>
          <p><strong>制造商:</strong> ${detail.eqmanufacture || 'N/A'}</p>
          <p><strong>购买日期:</strong> ${detail.eqtime ? detail.eqtime.split('T')[0] : 'N/A'}</p>
        </div>
      `, `设备 "${detail.eqname || 'N/A'}" 详情`, {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '确定',
        customClass: 'device-detail-messagebox', // 为了更好的样式控制
      });
  } catch (error) {
    console.error('获取设备详情失败:', error);
    ElMessage.error(`获取设备详情失败: ${error.message || '未知错误'}`);
  }
};

const goToFaultProcess = () => {
    router.push({ path: '/fault/process' });
    ElMessage.info('跳转到故障处理页面');
};
</script>

<style scoped>
/* 样式保持不变 */
.device-monitor-container {
  padding: 20px;
  background-color: var(--el-bg-color-page);
}

.monitor-overview-card,
.chart-card,
.status-list-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-statistic {
  text-align: center;
}

.pagination-footer {
    display: flex;
    justify-content: flex-end;
    margin-top: 15px;
}
</style>
